package ise_demo_java;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;


/**
 * 语音评测 WebAPI 接口调用示例
 * <p>
 * 运行方法：直接运行 main() 即可
 * <p>
 * 结果： 控制台输出语音评测结果信息
 *
 * @author iflytek
 */
public class ise {
    // 合成webapi接口地址
    private static final String WEBISE_URL = "http://api.xfyun.cn/v1/service/v1/ise";
    // 应用ID
    private static final String APPID = "5d68cb7c";
    // 接口密钥
    private static final String API_KEY = "4eb8959a4febf325a6babe94dad0c1f6";
    // 评测文本
    private static final String TEXT = "It was two weeks before the Spring Festival and the shopping centre was crowded with shoppers.\n";
    // 音频编码
    private static final String AUE = "raw";
    // 采样率
    private static final String AUF = "audio/L16;rate=16000";
    // 结果级别
    private static final String RESULT_LEVEL = "simple";
    // 语种
    private static final String LANGUAGE = "en_us";
    // 评测种类
    private static final String CATEGORY = "read_sentence";
    // 音频文件地址
//    private static final String AUDIO_PATH = "http://bohandev.oss-cn-beijing.aliyuncs.com/upload/20190830/65c5935809ce44069042bcce5218d80f.wav";
    private static final String AUDIO_PATH = "D:/en_sentence.wav";

    /**
     * 评测 WebAPI 调用示例程序
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        Map<String, String> header = buildHttpHeader();
        byte[] audioByteArray = FileUtil.read(AUDIO_PATH);
//        byte[] audioByteArray = FileUtil.urlTobyte(AUDIO_PATH);
        String audioBase64 = new String(Base64.encodeBase64(audioByteArray), "UTF-8");
        String result = HttpUtil.doPost1(WEBISE_URL, header, "audio=" + URLEncoder.encode(audioBase64, "UTF-8") + "&text=" + URLEncoder.encode(TEXT, "UTF-8"));
        System.out.println("评测 WebAPI 接口调用结果：" + result);
        System.out.println("--------------------");
        System.out.println(out(result));
    }

    private static String out(String result) {
        String str = "";
        JSONObject object = JSON.parseObject(result);
        String code = (String) object.get("code");
        if (null != code && "0".equals(code)) {
            JSONObject object1 = (JSONObject) object.get("data");
            JSONObject object2 = (JSONObject) object1.get("read_sentence");
            JSONObject object3 = (JSONObject) object2.get("rec_paper");
            JSONObject object4 = (JSONObject) object3.get("read_chapter");
            String is_rejected = (String) object4.get("is_rejected");
            String except_info = (String) object4.get("except_info");
            if ("false".equals(is_rejected) && "0".equals(except_info)) {
                String total_score = (String) object4.get("total_score");
                str = "朗读得分：" + total_score;
            } else {
                str = "朗读有问题！！！别瞎读！";
                if ("28673".equals(except_info)) {
                    str = "无语音输入或音量太小";
                } else if ("28676".equals(except_info)) {
                    str = "检测到语音为乱说类型";
                } else if ("28680".equals(except_info)) {
                    str = "音频数据信噪比太低";
                } else if ("28690".equals(except_info)) {
                    str = "音频数据出现截幅";
                }
            }
        } else {
            str = "请求错误！code:" + code + " desc:" + object.get("desc");
        }
        return str;
    }

    /**
     * 组装http请求头
     */
    private static Map<String, String> buildHttpHeader() throws UnsupportedEncodingException {
        String curTime = System.currentTimeMillis() / 1000L + "";
        String param = "{\"auf\":\"" + AUF + "\",\"aue\":\"" + AUE + "\",\"result_level\":\"" + RESULT_LEVEL + "\",\"language\":\"" + LANGUAGE + "\",\"category\":\"" + CATEGORY + "\"}";
        String paramBase64 = new String(Base64.encodeBase64(param.getBytes("UTF-8")));
        String checkSum = DigestUtils.md5Hex(API_KEY + curTime + paramBase64);
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        header.put("X-Param", paramBase64);
        header.put("X-CurTime", curTime);
        header.put("X-CheckSum", checkSum);
        header.put("X-Appid", APPID);
        return header;
    }
}
